package com.ncu.utils.file;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;

@Data
@Component
public class QiniuUtils {

    public static final String url = "http://rg8731xaj.hn-bkt.clouddn.com/";  //七牛云图片服务器域名（有效1个月）

    @Value("${qiniu.accessKey}")
    private  String accessKey;      //类似账号，在七牛云个人空间---密钥管理获取
    @Value("${qiniu.accessSecretKey}")
    private  String accessSecretKey;   //类似密码
    public boolean upload(MultipartFile file, String fileName){

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());  //根据自己的对象空间的地址选（华为）
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传 (个人存储空间名字)
        String bucket = "xlfblogs";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            //fileName格式是 xxxx/.../xxxxx.扩展名  在前面不要加/
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return false;
    }

    public boolean exists(String filePath){
        return false;
//        //构造一个带指定 Region 对象的配置类
//        Configuration cfg = new Configuration(Region.region0());
////...其他参数参考类注释
//        Auth auth = Auth.create(accessKey, accessSecretKey);
//
//        //...生成上传凭证 (个人存储空间名字)
//        String bucket = "xlfblogs";
//        BucketManager bucketManager = new BucketManager(auth, cfg);
//        try {
//            FileInfo fileInfo = bucketManager.stat(bucket, filePath);
////            System.out.println(fileInfo.hash);
////            System.out.println(fileInfo.fsize);
////            System.out.println(fileInfo.mimeType);
////            System.out.println(fileInfo.putTime);
//            if(fileInfo!=null)
//                return true;
//        } catch (QiniuException ex) {
//
//        }
      //  return false;
    }
}

